"""
Copyright 2009, Jay Shurtz.

This is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of
the License, or (at your option) any later version.

This software is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this software; if not, write to the Free
Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA, or see the FSF site: http://www.fsf.org.

Special persistent history module. 
See http://docs.python.org/library/readline.html
"""  

HEAD_URL = "$HeadURL: https://taggle.jira.com/svn/TOOLS/trunk/python_modules/custom_history.py $"
REVISION = "$Revision: 1812 $"
AUTHOR = "$Author: jayshurtz $"
DATE = "$Date: 2010-07-14 13:40:55 +1000 (Wed, 14 Jul 2010) $"
ID = "$Id: custom_history.py 1812 2010-07-14 03:40:55Z jayshurtz $"
version = " ".join(ID.split()[2:4])


import atexit
from os.path import join, splitext, extsep

from os import environ
HOME_DIR = environ.get("HOME", "")
del environ
DEFAULT_FILE = join(HOME_DIR, __file__)
DEFAULT_LENGTH = 5000
HISTORY_EXT = "pyhist"

try:
    import readline
except ImportError, e:
    from os import name
    badPlatform = "Custom history does not work on the '" + name + "' platform.  Try installing readline or pyreadline."
    def hist():
        print badPlatform
    def historyFileName(fileName):
        return badPlatform
    def setupSimpleHistory(histfile=DEFAULT_FILE, length=DEFAULT_LENGTH):
        print 'Warning: ' + badPlatform

else:

    def historyFileName(fileName):
        """ Convert a file name & extension to the custom history version.
            Example:  'blabla.py' -> 'blabla.pyhist'.
        """
        if not fileName.endswith(HISTORY_EXT):
            fileName = splitext(fileName)[0]+extsep+HISTORY_EXT
        return fileName

    def setupSimpleHistory(histfile=DEFAULT_FILE, length=DEFAULT_LENGTH):
        """ Simple method for immediately loading history from a file & updating it 
            when exiting the python console.
            Rather than always implicitly setting up a universal python history,
            this method allows modules to explicitly use their own independant history files.
            'histfile' specifies the file to use. File extensions will automatically 
            be replaced with the history file extension.
            'length' specifies the maximum history length when updating all files (negative is unlimited.)
        """
        histfile = historyFileName(histfile)
        # XXX Retire any existing history files in use (_exithandlers) ?
        readline.set_history_length(length)
        atexit.register(readline.write_history_file, histfile)
        #readline.clear_history()   # XXX arg for fresh start ?
        try:
            readline.read_history_file(histfile)
        except IOError:
            pass # If histfile is not found, we simply don't get any history.
        #print "Saving history to file: " + histfile

    try:
        def hist(length=None, format=None):    # TODO implement as "".format() for higher versions of python.
            """ Return items in history.
                'length' specifies the number of items to return up to the most recent item (default all.)
                'format' specifies the number of spaces used to print the item count (default exactly enough, set to 0 for no count.)
            """
            last = readline.get_current_history_length()
            first = 0
            if length is not None and length > 0 and length < last:
                first = last-length
            if format is None:
                format = len(str(last))
            history = ""
            if format < 1:
                history = "\n".join([readline.get_history_item(i) for i in range(first+1, last+1)])
            else:
                history = "\n".join([" "*(format-len(str(i))) + str(i) + "  " + readline.get_history_item(i) for i in range(first+1, last+1)])
            print history
    except AttributeError, e:   # pyreadline has no "get_history_item" method, and "get_current_history_length" is "get_history_length".
        pass    # This function is not a big deal anyway.
    #else:
    #    print hist.func_name + "() function enabled."   # Print helpful instructions.  # TODO use sys.stdout instead of print ?


if __name__ == '__main__':
    
    print 'Testing!'
    setupSimpleHistory()
    hist()
    hist(0,0)
    hist(1,1)

